﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Discuz.Toolkit;
using Icst.Leaflike.Discuz;

namespace Icst.Leaflike.Web
{
    public partial class login : pagebase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                lblError.Text = string.Empty;
                liDivErrorMessage.Style[HtmlTextWriterStyle.Display] = "none";
            }
        }

        protected void loginButton_Click(object sender, EventArgs e)
        {
            string userName = txtUsername.Value.Trim();
            string password = txtPassword.Value.Trim();
            string returnUrl = this.Para("returnUrl", "index.htm");

            if(!VerifyCheck(txtVerifyCode.Value.Trim()))
            {
                lblError.Text = "验证码错误，请重试";
                liDivErrorMessage.Style[HtmlTextWriterStyle.Display] = "block";
            }
            else
            {
                if (DoLogin(userName, password))
                {
                    this.Redirect(returnUrl);
                }
                else
                {
                    lblError.Text = "登录失败，请重试";
                    liDivErrorMessage.Style[HtmlTextWriterStyle.Display] = "block";
                }
            }
        }

        private bool VerifyCheck(string verifyCode)
        {
            string targetverifyCode = Session["VerificationCode"]!=null?(string)Session["VerificationCode"]:string.Empty;
            return (!string.IsNullOrEmpty(targetverifyCode) &&
                verifyCode.Equals(targetverifyCode, StringComparison.InvariantCultureIgnoreCase));
        }

        private bool DoLogin(string userName, string password)
        {
            try
            {
                if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
                    return false;

                User user = null;
                return UserAccount.Login(userName, password, out user);

            }
            catch
            {
                return false;
            }

            return false;
        }
    }
}
